<?php

//父菜单
function up_name($id) {
    if ($id != 0) {
        $menu = D('BackMenu')->getMenuName($id);
        $menu_name = $menu['name'];
    } else {
        $menu_name = "无";
    }
    return $menu_name;
}

//取得信息
function get_info($url, $options = array()) {
    $options[CURLOPT_FOLLOWLOCATION] = true;

    $options[CURLOPT_TIMEOUT] = 1;
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    $html = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    return $info;
}

function get_html($url, $options = array()) {
    $options[CURLOPT_FOLLOWLOCATION] = true;
    $options[CURLOPT_RETURNTRANSFER] = true;
    $options[CURLOPT_TIMEOUT] = 5;
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $html = curl_exec($ch);
    curl_close($ch);
    if ($html === false) {
        return false;
    }
    return $html;
}

function get_matches($pattern, $html, $err_msg, $multi = false, $flags = 0, $offset = 0) {
    if (!$multi) {
        if (preg_match($pattern, $html, $matches, $flags, $offset)) {
            echo iconv("utf-8", "gb2312//IGNORE", $err_msg . "! 错误信息: " . get_preg_err_msg() . "\n");
            return false;
        }
    } else {
        if (!preg_match_all($pattern, $html, $matches, $flags, $offset)) {
            echo iconv("utf-8", "gb2312//IGNORE", $err_msg . "! 错误信息: " . get_preg_err_msg() . "\n");
            return false;
        }
    }
    return $matches;
}

function get_preg_err_msg() {
    $error_code = preg_last_error();
    switch ($error_code) {
        case PREG_NO_ERROR :
            $err_msg = 'PREG_NO_ERROR';
            break;
        case PREG_INTERNAL_ERROR:
            $err_msg = 'PREG_INTERNAL_ERROR';
            break;
        case PREG_BACKTRACK_LIMIT_ERROR:
            $err_msg = 'PREG_BACKTRACK_LIMIT_ERROR';
            break;
        case PREG_RECURSION_LIMIT_ERROR:
            $err_msg = 'PREG_RECURSION_LIMIT_ERROR';
            break;
        case PREG_BAD_UTF8_ERROR:
            $err_msg = 'PREG_BAD_UTF8_ERROR';
            break;
        case PREG_BAD_UTF8_OFFSET_ERROR:
            $err_msg = 'PREG_BAD_UTF8_OFFSET_ERROR';
            break;
        default:
            return '未知错误!';
    }
    return $err_msg . ': ' . $error_code;
}

/**
 * collect
 * 采集方法
 * 
 * @access public
 * @param int $id 采集规则id
 * @return array 
 * @author  fangzheng<zheng.fang@wemax.org> 
 */
function collect($id) {
    $return = false;
    if ($id) {
        $collect = D('CollectRelation')->relation(true)->find($id);
        if ($collect['is_active'] == 0) {
            //取得数据库最大id
            set_time_limit(0);
            $last_posion = (int) $collect['last_position'];
            $count = $last_posion + $collect['count'];

            //循环，从上次结束的地方开始
            $root_url = $collect['url'];
            for (; $last_posion < $count; $last_posion++) {
                //url
                $url = $collect['url'] . $last_posion . ".html";

                //cookie保存目录
                $cookdir = '/Public/tmp';

                $options[CURLOPT_FOLLOWLOCATION] = true;
                $html = get_html($url);
                if (!$html) {
                    echo iconv("utf-8", "gb2312//IGNORE", "连接失败<br>");
                    continue;
                }
                $matches = get_matches($collect['not_find'], $html, '没有找到404<br>', false);

                if ($matches) {
                    echo "404";
                    continue;
                }
                $matches = get_matches(htmlspecialchars_decode($collect['content']), $html, '没有找到链接<br>', true);
                if ($matches) {
                    echo iconv("utf-8", "gb2312//IGNORE", "文章:&nbsp;&nbsp;&nbsp;" . $collect['name'] . $last_posion . '<br>');
                    //获取采集各个字段值
                    foreach ($collect['rule'] as $key => $rule) {
                        if (preg_match_all(htmlspecialchars_decode($rule['regex']), $html, $match_value)) {
                            $match_value = $rule['strip_tags'] ? trim($match_value[0][0]) : trim(strip_tags($match_value[0][0]));
                            $collect['code'] && $match_value = iconv($collect['code'], "utf-8//IGNORE", $match_value);
                            $data[$rule['the_field']] = $match_value;
                            $match_value = null;
                        }
                    }
                    $data['title'] || $data['title'] = $collect['name'] . $last_posion;
                    $data['publish_time'] = $data['publish_time'] ? strtotime($data['publish_time']) : time();
                    $data['collect_time'] = $data['update_time'] = time();

                    M('articles')->add($data);
                    unset($data);
                }
            }
            $result = M('collect')->where('id=' . $id)->setField('last_position', $last_posion);
        }
    }
    return $return;
}

//function date_to_unixtime($date, $timezone = 'PRC') {
//    $datetime = new DateTime($date, new DateTimeZone($timezone));
//    return $datetime->format('U');
//}
//
//function unixtime_to_date($unixtime, $timezone = 'PRC') {
//    $datetime = new DateTime("@$unixtime"); //DateTime类的bug，加入@可以将Unix时间戳作为参数传入
//    $datetime->setTimezone(new DateTimeZone($timezone));
//    return $datetime->format("Y-m-d H:i:s");
//}

/**
 * 获取配置的分组
 * @param string $group 配置分组
 * @return string
 */
function get_config_group($group = 0) {
    $list = C('CONFIG_GROUP_LIST');
    return $group ? $list[$group] : '';
}

/**
 * select返回的数组进行整数映射转换
 *
 * @param array $map  映射关系二维数组  array(
 *                                          '字段名1'=>array(映射关系数组),
 *                                          '字段名2'=>array(映射关系数组),
 *                                           ......
 *                                       )
 * @return array
 *
 *  array(
 *      array('id'=>1,'title'=>'标题','status'=>'1','status_text'=>'正常')
 *      ....
 *  )
 *
 */
function int_to_string(&$data, $map = array('status' => array(1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿'))) {
    if ($data === false || $data === null) {
        return $data;
    }
    $data = (array) $data;
    foreach ($data as $key => $row) {
        foreach ($map as $col => $pair) {
            if (isset($row[$col]) && isset($pair[$row[$col]])) {
                $data[$key][$col . '_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

//字符串截取
function str_cut($sourcestr, $cutlength, $suffix = '...') {
    $str_length = strlen($sourcestr);
    if ($str_length <= $cutlength) {
        return $sourcestr;
    }
    $returnstr = '';
    $n = $i = $noc = 0;
    while ($n < $str_length) {
        $t = ord($sourcestr[$n]);
        if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $i = 1;
            $n++;
            $noc++;
        } elseif (194 <= $t && $t <= 223) {
            $i = 2;
            $n += 2;
            $noc += 2;
        } elseif (224 <= $t && $t <= 239) {
            $i = 3;
            $n += 3;
            $noc += 2;
        } elseif (240 <= $t && $t <= 247) {
            $i = 4;
            $n += 4;
            $noc += 2;
        } elseif (248 <= $t && $t <= 251) {
            $i = 5;
            $n += 5;
            $noc += 2;
        } elseif ($t == 252 || $t == 253) {
            $i = 6;
            $n += 6;
            $noc += 2;
        } else {
            $n++;
        }
        if ($noc >= $cutlength) {
            break;
        }
    }
    if ($noc > $cutlength) {
        $n -= $i;
    }
    $returnstr = substr($sourcestr, 0, $n);
    if (substr($sourcestr, $n, 6)) {
        $returnstr = $returnstr . $suffix; //超过长度时在尾处加上省略号
    }
    return $returnstr;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = & $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array()) {
    if (is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if (isset($reffer[$child])) {
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby = 'asc');
    }
    return $list;
}

function fix_image_url($url) {
    $flag = preg_match('/\/' . C('DB_NAME') . '/', $url);
    if ($flag) {
        $arr = explode('/' . C('DB_NAME'), $url);
        $new_url = $arr[1];
    } else {
        $new_url = $url;
    }
    return $new_url;
}

function fix_image_shuiying($url) {
    $flag = preg_match('/\/' . C('DB_NAME') . '/', $url);
    if ($flag) {
        $arr = explode('/' . C('DB_NAME'), $url);
        $new_url = $arr[0] . $arr[1];
    } else {
        $new_url = $url;
    }
    return $new_url;
}

function getUser($userid) {
    $user = M('users');
    $condition['id'] = $userid;
    $name = $user->where($condition)->getField('name');
    if ($name)
        return $name;
    else
        return;
}

/**
 * replace_image 替换图片 2014.7.12
 * @param string $matches 匹配出来的内容
 * @return 返回字符串名字
 */
function replace_image($transformation, $matches) {
    $image = $matches[0];
    $image_water = $matches[1]; //需要添加水印的图片
    $do_thumb = add_water($transformation['site_id'], $image_water);
    if ($do_thumb['status'] == 0) {
        $savename = $image;
    } else {
        $file_names = explode('.', $image);
        $savename = $file_names[0] . '_' . $transformation['site_id'] . '.' . $file_names[1];
    }
    return $savename;
}

function add_water($site_id, $thumb) {
    ob_clean();
    $thumb = "." . fix_image_url($thumb);

    $return = array(
        'status' => 0,
        'thumb' => $thumb
    );
    if (empty($thumb)) {
        return $return;
    }
    $site = M('Site');
    if ($site_id) {
        $water_setting = $site->where(array('id' => $site_id))->getField('watermark');
        if ($water_setting) {
            $setting = unserialize(htmlspecialchars_decode($water_setting));
            if ($setting['watermark_enable']) {//如果水印没有开启，直接返回传过来路径
                $image = new \Think\Image();
                $watermark_pos = $setting['watermark_pos'] ? $setting['watermark_pos'] : 1;

                $file_names = explode('.', $thumb);
                $savename = ltrim($file_names[1], '/') . '_' . $site_id . '.' . $file_names[2];
                if ($setting['watemard_text']) {
                    $watemard_text_size = $setting['watemard_text_size'] ? $setting['watemard_text_size'] : 12;
                    $watemard_text_color = $setting['watemard_text_color'] ? $setting['watemard_text_color'] : '#FFFFF';
                    $watemard_text_face = $setting['watemard_text_face'] ? $setting['watemard_text_face'] : 'simsun.ttc';
                    $image->open('.' . $thumb)->text($setting['watemard_text'], './Public/Font/' . $watemard_text_face, $watemard_text_size, $watemard_text_color, $watermark_pos)->save('./' . $savename);
                }

                if ($setting['watermark_img']) {
                    $setting['watermark_img'] = "." . $setting['watermark_img'];
                    $watermark_pct = $setting['watermark_pct'] ? $setting['watermark_pct'] : 50;

                    $image->open($thumb)->water($setting['watermark_img'], $watermark_pos, $watermark_pct)->save($savename);
                }

                //返回加水印的图片路径
                return array(
                    'status' => 1,
                    'thumb' => '/' . C('DB_NAME') . '/' . $savename
                );
            } else {
                return $return;
            }
        } else {
            return $return;
        }
    } else {
        return $return;
    }
}
function do_fake($type, $site_id, $content, $fake_arr = array()) {
    $site = M('SiteFake');
    $condition['site_id'] = $site_id;
    $vo_site = $site->where($condition)->field('fake_pretitle,isdefault_pretitle,fake_suffixtitle,isdefault_suffixtitle,fake_prepara,isdefault_prepara,fake_suffixpara,isdefault_suffixpara')->find();
    if ($vo_site) {
        if ($type == 1) {//伪原创标题处理
            if ($vo_site['isdefault_pretitle'] && $fake_arr['isdefault_pretitle'] && (mb_strpos($content, $vo_site['fake_pretitle']) === FALSE))
                $content = $vo_site['fake_pretitle'] . $content;
            if ($vo_site['isdefault_suffixtitle'] && $fake_arr['isdefault_suffixtitle'] && (mb_strpos($content, $vo_site['fake_suffixtitle']) === FALSE))
                $content = $content . $vo_site['fake_suffixtitle'];
            return $content;
        } elseif ($type == 2) {//伪原创段落处理
            if ($vo_site['isdefault_prepara'] && $fake_arr['isdefault_prepara'] && (mb_strpos($content, $vo_site['fake_prepara']) === FALSE))
                $content = $vo_site['fake_prepara'] . $content;
            if ($vo_site['isdefault_suffixpara'] && $fake_arr['isdefault_suffixpara'] && (mb_strpos($content, $vo_site['fake_suffixpara']) === FALSE))
                $content = $content . $vo_site['fake_suffixpara'];
            return $content;
        }else {
            return;
        }
    } else {
        return;
    }
}

//过滤词语和外链替换 --free_dream-- 2014.4.21
function filter_words($content, $site_id, $fake_arr = array()) {
    $content = match_image($content, $site_id);

    $siteWord = M('SiteWord');
    $siteOuterchain = M('SiteOuterchain');
    import("Think.KeyReplace");
    $wordInfo = M('Site')->where(array('id' => $site_id))->field('isword,word_type')->find();

    $vo_site_outerchain = $siteOuterchain->where(array('status' => 1))->order('rand()')->limit('500')->getField('title,outer_chain');
    //伪原创添加
    $content = do_fake(2, $site_id, $content, $fake_arr);

    //词库词替换
    if ($wordInfo['isword'] && $fake_arr['isword'] && $wordInfo['word_type']) {//词库分类存在
        $condition_site_word['type_id'] = array('in', $wordInfo['word_type']);
        $vo_site_word = $siteWord->where($condition_site_word)->order('rand()')->limit('500')->getField('find,replacement');
        $find = array_keys($vo_site_word);
        $replace = array_values($vo_site_word);
        $content = str_replace($find, $replace, $content); //关键词替换
    }
    //外链替换
    $key = new \Think\KeyReplace($content, $vo_site_outerchain, true, '', TRUE); //外链替换
    $content = $key->getResultText();
    return $content;
}

function get_list_field($data, $grid, $model) {

    // 获取当前字段数据
    foreach ($grid['field'] as $field) {
        $array = explode('|', $field);
        $temp = $data[$array[0]];
        // 函数支持
        if (isset($array[1])) {
            $temp = call_user_func($array[1], $temp);
        }
        $data2[$array[0]] = $temp;
    }
    if (!empty($grid['format'])) {
        $value = preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data2) {
            return $data2[$match[1]];
        }, $grid['format']);
    } else {
        $value = implode(' ', $data2);
    }

    // 链接支持
    if (!empty($grid['href'])) {
        $links = explode(',', $grid['href']);
        foreach ($links as $link) {
            $array = explode('|', $link);
            $href = $array[0];
            if (preg_match('/^\[([a-z_]+)\]$/', $href, $matches)) {
                $val[] = $data2[$matches[1]];
            } else {
                $show = isset($array[1]) ? $array[1] : $value;
                // 替换系统特殊字符串
                $href = str_replace(
                        array('[DELETE]', '[EDIT]', '[MODEL]'), array('del?ids=[id]&model=[MODEL]', 'edit?id=[id]&model=[MODEL]', $model['id']), $href);

                // 替换数据变量
                $href = preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data) {
                    return $data[$match[1]];
                }, $href);

                $val[] = '<a href="' . U($href) . '">' . $show . '</a>';
            }
        }
        $value = implode(' ', $val);
    }
    return $value;
}

// 获取模型名称
function get_model_by_id($id) {
    return $model = M('Model')->getFieldById($id, 'title');
}

// 获取属性类型信息
function get_attribute_type($type = '') {
    // TODO 可以加入系统配置
    static $_type = array(
        'num' => array('数字', 'int(10) UNSIGNED NOT NULL'),
        'string' => array('字符串', 'varchar(255) NOT NULL'),
        'textarea' => array('文本框', 'text NOT NULL'),
        'datetime' => array('时间', 'int(10) NOT NULL'),
        'bool' => array('布尔', 'tinyint(2) NOT NULL'),
        'select' => array('枚举', 'char(50) NOT NULL'),
        'radio' => array('单选', 'char(10) NOT NULL'),
        'checkbox' => array('多选', 'varchar(100) NOT NULL'),
        'editor' => array('编辑器', 'text NOT NULL'),
        'picture' => array('上传图片', 'int(10) UNSIGNED NOT NULL'),
        'file' => array('上传附件', 'int(10) UNSIGNED NOT NULL'),
    );
    return $type ? $_type[$type][0] : $_type;
}

/**
 * 获取对应状态的文字信息
 * @param int $status
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_status_title($status = null) {
    if (!isset($status)) {
        return false;
    }
    switch ($status) {
        case -1 : return '已删除';
            break;
        case 0 : return '禁用';
            break;
        case 1 : return '正常';
            break;
        case 2 : return '待审核';
            break;
        default : return false;
            break;
    }
}

// 获取数据的状态操作
function show_status_op($status) {
    switch ($status) {
        case 0 : return '启用';
            break;
        case 1 : return '禁用';
            break;
        case 2 : return '审核';
            break;
        default : return false;
            break;
    }
}

/**
 * 获取文档的类型文字
 * @param string $type
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_document_type($type = null) {
    if (!isset($type)) {
        return false;
    }
    switch ($type) {
        case 1 : return '目录';
            break;
        case 2 : return '主题';
            break;
        case 3 : return '段落';
            break;
        default : return false;
            break;
    }
}

/**
 * 获取配置的类型
 * @param string $type 配置类型
 * @return string
 */
function get_config_type($type = 0) {
    $list = C('CONFIG_TYPE_LIST');
    return $list[$type];
}



/**
 * 动态扩展左侧菜单,base.html里用到
 * @author 朱亚杰 <zhuyajie@topthink.net>
 */
function extra_menu($extra_menu, &$base_menu) {
    foreach ($extra_menu as $key => $group) {
        if (isset($base_menu['child'][$key])) {
            $base_menu['child'][$key] = array_merge($base_menu['child'][$key], $group);
        } else {
            $base_menu['child'][$key] = $group;
        }
    }
}

/**
 * 获取参数的所有父级分类
 * @param int $cid 分类id
 * @return array 参数分类和父类的信息集合
 * @author huajie <banhuajie@163.com>
 */
function get_parent_category($cid) {
    if (empty($cid)) {
        return false;
    }
    $cates = M('Category')->where(array('status' => 1))->field('id,title,pid')->order('sort')->select();
    $child = get_category($cid); //获取参数分类的信息
    $pid = $child['pid'];
    $temp = array();
    $res[] = $child;
    while (true) {
        foreach ($cates as $key => $cate) {
            if ($cate['id'] == $pid) {
                $pid = $cate['pid'];
                array_unshift($res, $cate); //将父分类插入到数组第一个元素前
            }
        }
        if ($pid == 0) {
            break;
        }
    }
    return $res;
}

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1) {
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 获取当前分类的文档类型
 * @param int $id
 * @return array 文档类型数组
 * @author huajie <banhuajie@163.com>
 */
function get_type_bycate($id = null) {
    if (empty($id)) {
        return false;
    }
    $type_list = C('DOCUMENT_MODEL_TYPE');
    $model_type = M('Category')->getFieldById($id, 'type');
    $model_type = explode(',', $model_type);
    foreach ($type_list as $key => $value) {
        if (!in_array($key, $model_type)) {
            unset($type_list[$key]);
        }
    }
    return $type_list;
}

/**
 * 获取当前文档的分类
 * @param int $id
 * @return array 文档类型数组
 * @author huajie <banhuajie@163.com>
 */
function get_cate($cate_id = null) {
    if (empty($cate_id)) {
        return false;
    }
    $cate = M('Category')->where('id=' . $cate_id)->getField('title');
    return $cate;
}

// 分析枚举类型配置值 格式 a:名称1,b:名称2
function parse_config_attr($string) {
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if (strpos($string, ':')) {
        $value = array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k] = $v;
        }
    } else {
        $value = $array;
    }
    return $value;
}

// 获取子文档数目
function get_subdocument_count($id = 0) {
    return M('Document')->where('pid=' . $id)->count();
}

// 分析枚举类型字段值 格式 a:名称1,b:名称2
// 暂时和 parse_config_attr功能相同
// 但请不要互相使用，后期会调整
function parse_field_attr($string) {
    if (0 === strpos($string, ':')) {
        // 采用函数定义
        return eval(substr($string, 1) . ';');
    }
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if (strpos($string, ':')) {
        $value = array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k] = $v;
        }
    } else {
        $value = $array;
    }
    return $value;
}

/**
 * 获取行为数据
 * @param string $id 行为id
 * @param string $field 需要获取的字段
 * @author huajie <banhuajie@163.com>
 */
function get_action($id = null, $field = null) {
    if (empty($id) && !is_numeric($id)) {
        return false;
    }
    $list = S('action_list');
    if (empty($list[$id])) {
        $map = array('status' => array('gt', -1), 'id' => $id);
        $list[$id] = M('Action')->where($map)->field(true)->find();
    }
    return empty($field) ? $list[$id] : $list[$id][$field];
}

/**
 * 根据条件字段获取数据
 * @param mixed $value 条件，可用常量或者数组
 * @param string $condition 条件字段
 * @param string $field 需要返回的字段，不传则返回整个数据
 * @author huajie <banhuajie@163.com>
 */
function get_document_field($value = null, $condition = 'id', $field = null) {
    if (empty($value)) {
        return false;
    }

    //拼接参数
    $map[$condition] = $value;
    $info = M('Model')->where($map);
    if (empty($field)) {
        $info = $info->field(true)->find();
    } else {
        $info = $info->getField($field);
    }
    return $info;
}

/**
 * 获取行为类型
 * @param intger $type 类型
 * @param bool $all 是否返回全部类型
 * @author huajie <banhuajie@163.com>
 */
function get_action_type($type, $all = false) {
    $list = array(
        1 => '系统',
        2 => '用户',
    );
    if ($all) {
        return $list;
    }
    return $list[$type];
}

function get_word_type($id) {
    if (empty($id))
        return;
    $wordtype_title = M('SiteWordType')->getFieldById($id, 'title');
    if (!empty($wordtype_title)) {
        return $wordtype_title;
    } else {
        return;
    }
}

function loseSpace($pcon) {
    $pcon = preg_replace("/ /", "", $pcon);
    $pcon = preg_replace("/&nbsp;/", "", $pcon);
    $pcon = preg_replace("/　/", "", $pcon);
    $pcon = preg_replace("/\r\n/", "", $pcon);
    $pcon = str_replace(chr(13), "", $pcon);
    $pcon = str_replace(chr(10), "", $pcon);
    $pcon = str_replace(chr(9), "", $pcon);
    return $pcon;
}



/**
 * sendRemoteContent 向远程站点发送内容
 * @param type $siteContentSite
 * @param type $condition
 * @param type $sendData
 * @param object $siteContentLog 站点日志表
 */
function sendRemoteContent($sendData, $siteContentLog, $do = 'insert') {

    $sendData['content'] = str_replace('\'', '"', $sendData['content']); //正则转换单引号为双引号

    $data = array('usr' => 'mofei', 'pwd' => '123', 'do' => $do, 'data' => $sendData);
    // 设置URL和相应的选项
    $ch = curl_init();
    $timeout = 25;
    curl_setopt($ch, CURLOPT_URL, $sendData['site_url']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

    // 抓取URL并把它传递给浏览器
    $result = curl_exec($ch);
    $rel = json_decode($result, TRUE);
    //关闭cURL资源，并且释放系统资源
    curl_close($ch);
    if ($rel['status'] == 1) {
        if ($do != 'delete') {
            $siteContent = M('SiteContent');
            $siteQueueContent = M('SiteQueueContent');
            if ($rel['remote_content_id']) {
                $remote_content_url = empty($rel['remote_content_url']) ? '' : $rel['remote_content_url'];
                $effect = $siteContent->where(array('id' => $sendData['content_id']))->setField(array('remote_content_id' => $rel['remote_content_id'], 'remote_content_url' => $remote_content_url, 'update_time' => time()));
                if ($effect !== FALSE) {
                    $siteQueueContent->where(array('content_id' => $sendData['content_id']))->delete();
                }
            } else {
                $siteQueueContent->where(array('content_id' => $sendData['content_id']))->delete();
            }
        }
        $siteContentLog->add(array('weburl' => $sendData['weburl'], 'message' => $rel['message'], 'logsql' => $rel['do_sql'], 'createtime' => time(), 'status' => 1));
    } else {
        $siteContentLog->add(array('weburl' => $sendData['weburl'], 'message' => $sendData['title'] . $rel['message'] . $result, 'logsql' => $rel['do_sql'], 'createtime' => time(), 'status' => 0));
    }
}

/**
 * sendRemoteContent 向远程站点发送内容
 * @param type $siteContentSite
 * @param type $condition
 * @param type $sendData
 * @param object $siteContentLog 站点日志表
 */
function getRemoteHits($sendData, $siteContentLog, $do = 'gethits') {

    $data = array('usr' => 'mofei', 'pwd' => '123', 'do' => $do, 'data' => $sendData);
    // 设置URL和相应的选项
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $sendData['site_url']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

// 抓取URL并把它传递给浏览器
    $result = curl_exec($ch);
    $rel = json_decode($result, TRUE);
    //关闭cURL资源，并且释放系统资源
    curl_close($ch);
    if ($rel['status'] == 1) {
        $siteContent = M('SiteContent');
        $siteContent->where(array('id' => $sendData['content_id']))->setField(array('hits' => $rel['hits'], 'hits_update_time' => time()));
    } else {
        $siteContentLog->add(array('weburl' => $sendData['weburl'], 'message' => $result, 'logsql' => $rel['do_sql'], 'createtime' => time(), 'status' => 0));
    }
}

/**
 * match_image 匹配图片 2014.7.12
 * @param string $content 编辑器内容
 */
function match_image($content, $site_id) {
    $create_function = 'curry';
    $transform = array('site_id' => $site_id);
    $callback = $create_function('replace_image', 5);
    $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
    $content = preg_replace_callback($pattern, $callback($transform), $content);
    return $content;
}

/**
 * 创建函数
 * @param type $func
 * @param type $arity
 * @return type
 */
function curry($func, $arity) {
    return create_function('', "
         \$args = func_get_args();
         if(count(\$args) >= $arity)
             return call_user_func_array('$func', \$args);
         \$args = var_export(\$args, 1);
         return create_function('','
             \$a = func_get_args();
             \$z = ' . \$args . ';
             \$a = array_merge(\$z,\$a);
             return call_user_func_array(\'$func\', \$a);
         ');
     ");
}


function getSite($site_id) {
    $site = M('Site');
    $siteTitle = $site->getFieldById($site_id, 'title');
    if ($siteTitle)
        return $siteTitle;
    else
        return;
}

?>
    

